<template>
    <!-- <n-data-table :class='$style.table' :columns='columns' :data='data' v-bind='attrs'></n-data-table> -->
    <!-- <ATable :pagination='false' :columns='columns' :data-source='data'></ATable> -->
    <div :class='[$style.batch, selectedCount > 0 ? $style.show : ""]'>
        <template v-if="selectionButtons">
            <template v-for="(btn, index) in selectionButtons" :key="index">
                <template v-if="btn.button == 'delete'">
                    <a-button danger @click='doBatchDelete(btn.func)'>{{$t('delete')}}</a-button>
                </template>
            </template>
        </template>
        <template v-if='slots["$selection"]'>
            <template v-for='(vnode, index) in slots["$selection"]()' :key='index'>
                <component :is='vnode' />
            </template>
        </template>
    </div>

    <a-table size="small" :bordered="bordered" :pagination='false' :rowKey="rowKey" :columns='tableColumns' :data-source='data' :row-selection='selectionOptions' :scroll='{x:"max-content"}'>
        <template #bodyCell="{ text, record, index, column }">
            <template v-if='column.dataIndex == "$action"'>
                <div :class='$style.action'>
                    <template v-if='column.$detail'>
                        <BTextButton type='primary' @click='column.$detail(record, index)'>查看</BTextButton>
                    </template>
                    <template v-if='column.$edit'>
                        <BTextButton type='primary' @click='column.$edit(record, index)'>{{$t('edit')}}</BTextButton>
                    </template>
                    <template v-if='column.$delete'>
                        <BTextButton type='error' :loading='loadingIndex == index' @click='doDelete(column, record, index)'>{{$t('delete')}}</BTextButton>
                    </template>
                    <template v-if='slots.$action'>
                        <slot name='$action' :text='text' :record='record' :index='index' :column='column'></slot>
                    </template>
                </div>
            </template>
            <template v-else-if='slots[column.dataIndex]'>
                <slot :name='column.dataIndex' :text='text' :record='record' :index='index' :column='column'></slot>
            </template>
            <template v-else-if='column.translate'>{{$t(record[column.dataIndex])}}</template>
        </template>
        <template v-if="slots.expandedRowRender" #expandedRowRender="{ record }">
            <slot name='expandedRowRender' :record='record'></slot>
        </template>
    </a-table>
</template>

<script lang='ts' setup>
    import { ref, toRefs, computed, useSlots, reactive } from "vue";
    import { Modal } from "ant-design-vue";
    import TextButton from './TextButton.vue'
import { useI18nStore } from "@/store/i18n";

    const i18n = useI18nStore()


    const props = defineProps<{
        bordered? : boolean;
        rowKey? : string;
        nameKey? : string;
        columns : Column[];
        data : any[];
        rowSelection? : object | boolean;
        selectionButtons? : Array<SelectionButton>,
        [key:string] : any;
    }>()

    const emit = defineEmits<{
        (e : 'selectionChange', keys:any[], rows : any[]) : void;
    }>()



    const slots = useSlots()
    
    const loadingIndex = ref(-1)
    const tableColumns = ref<Column[]>([])

    const { columns, nameKey, rowKey, data } = toRefs(props)
    columns.value.forEach((col, index) => {
        if(col.hideInTable) return

        if(col.ellipsis) {
            col.ellipsis = {
                showTitle : true
            }
        }

        if(col.dataIndex == '$action') {
            if(!col.fixed) {col.fixed = 'right'}
            if(!col.width) {col.width = '150px'}
        }

        tableColumns.value.push(col)
    })

    const selectedCount = ref(0)

    const selectionOptions = ref<any>()

    if(props.rowSelection) {
        selectionOptions.value = {
            type : 'checkbox',
            selectedRowKeys : [],
            onChange(keys:any[], rows:any[]) {
                selectedCount.value = keys.length
                selectionOptions.value.selectedRowKeys = keys
                emit('selectionChange', keys, rows)
            }
        }

        if(typeof props.rowSelection == 'object') {
            selectionOptions.value = Object.assign(selectionOptions.value, props.rowSelection)
        }
        
    }

    


    function doDelete(column:Column, record:any, index:number) {
        let tipsName = nameKey?.value ? `【${record[nameKey.value]}】` : i18n.t('thisData')
        Modal.confirm({
            title : i18n.t('confirmDel', [tipsName]),
            onOk() {
                loadingIndex.value = index
                column.$delete(record, index).then(() => {
                    loadingIndex.value = -1
                })
                // try {
                //     await column.$delete(record, index)
                // } catch (error) {
                    
                // }

            }
        })
    }

    async function doBatchDelete(callback:(...params:any[]) => Promise<void>) {
        Modal.confirm({
            title : i18n.t('confirmDel', [i18n.t('selectedData')]),
            async onOk() {
                await callback()
            }
        })
    }


    defineExpose({
        cleanSelection(){
            if(props.rowSelection) {
                selectedCount.value = 0
                selectionOptions.value.selectedRowKeys = []
                emit('selectionChange', [], [])
            }
        }
    })

</script>


<style lang='scss' module>
    .action{
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        justify-content:center;
    }

    .batch{
        margin-bottom : 10px;
        display: none;
        gap: 10px;
        &.show{
            display: flex;
        }
    }
</style>